<?php

namespace App\Models;

use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Exception;
use Illuminate\Support\Facades\DB;

class Evaluate extends Model
{
    //评价表
    protected $table = 'c_evaluates';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 用户
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 课程
     */
    public function course()
    {
        return $this->belongsTo('App\Models\Course', 'goods_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 医师
     */
    public function doctor()
    {
        return $this->belongsTo('App\Models\Doctor', 'doctor_id');
    }

    public function reply()
    {
        return $this->belongsTo('App\Models\ReplyContent', 'id','evaluates_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 商品
     */
    public function goods()
    {
        return $this->belongsTo('App\Models\ProductGoods', 'goods_id');
    }

    public function setImagesAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['images'] = json_encode($gallery);
        }
    }

    public function getImagesAttribute($gallery)
    {
        return json_decode($gallery, true);
    }

//    public function setVideosAttribute($gallery)
//    {
//        if (is_array($gallery)) {
//            $this->attributes['videos'] = json_encode($gallery);
//        }
//    }
//
//    public function getVideosAttribute($gallery)
//    {
//        return json_decode($gallery, true);
//    }

    public function addEvaluateContent($filter)
    {
        try {
            $res = (new Order())->where([['id', '=', $filter['order_id']]])->first();
            if (!$res) {
                return "该订单不存在,不能评论";
            }
            $order_goods = (new OrderGoods())->where([['order_id','=',$res->id]])->first();
            $filter['work_id'] = $res->work_id;
            $tool = new Tool();
            DB::beginTransaction(); // 开始事务
            $info = $this->getInfos($filter);
            if (!empty($info)) {
                return "该用户已经评论过,不能重复评论";
            }
            $this->user_id = $filter['user_id'];
            $this->goods_id = $order_goods->goods_id;//$filter['goods_id'];
            $this->order_id = $filter['order_id'];
            $this->service_score = $filter['service_score'];
            if ($filter['types'] == 2) {
                $this->logis_score = $filter['logis_score'];
                $this->delivery_score = $filter['delivery_score'];
            }
            $this->score = $this->setScore($filter);
            $this->content = $filter['content'];
            $this->types = $filter['types'];
            $this->work_id = $filter['work_id'];
            $this->videos = isset($filter['videos']) ? $filter['videos'] : "";
            $this->images = isset($filter['images']) ? $tool::handelString($filter['images']) : "";
            if (isset($filter['videos']) || isset($filter['images'])) {
                $this->is_image = 1;
            }
            $this->anonymity_state = isset($filter['anonymity_state']) ? $filter['anonymity_state'] : 0;
            $res = $this->save();
            if (!$res) {
                DB::rollback(); // 回滚事务
                return "评论失败,请重新再试!";
            }
            if ($filter['types'] == 1) {
                $this->updateCourseScore($filter);
            } elseif ($filter['types'] == 2) {
                $this->updateGoodsScore($filter);
            } elseif ($filter['types'] == 3) {
                $this->updateDoctorScore($filter);
            }
            //修改评价状态
            $this->updateOrderEvaluate($filter['order_id']);
            //修改工作室评分
            self::updateWorkScore($filter);
            //工作室一条好评加成长值
            if($this->score > 3){ //一条好评
                $lt['work_id'] = $filter['work_id'];
                TaskComplete::add($lt, 7);
                GrowthNumberLog::add($lt, 7);
            }
            DB::commit(); // 提交事务
            return ['evaluate_id' => $this->id];
        } catch (wcexception $e) {
            echo $e->getmessage();
            $e->pro();
            DB::rollback(); // 回滚事务
        }
    }

    /***
     * @param $data
     * 更改工作室评分
     */
    public static function updateWorkScore($data)
    {
        $self = new DoctorWorks();
        $num = self::where([['work_id', '=', $data['work_id']]])->count("id");
        if ($num == 0) {
            return false;
        }
        $score = self::where([['work_id', '=', $data['work_id']]])->sum("score");
        $docworkscore = ceil($score / $num);
        return $self::where([['id', '=', $data['work_id']]])->update(["docworkscore" => $docworkscore]);
    }


    //计算分数
    public function setScore($data)
    {
        if ($data['types'] == 1 || $data['types'] == 3) { //课程和医师
            return $data['service_score'];
        } elseif ($data['types'] == 2) { //商品
            return ceil(($data['service_score'] + $data['logis_score'] + $data['delivery_score']) / 3);
        }
    }

    /****
     * @param $data
     * 计算课程评分
     */
    public function updateCourseScore($data)
    {
        $course = new Course();
        $total = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 1]])->count();
        $goods = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 1]])->where("score", '>', 2)->count();
        $course_score = number_format(($goods / $total) * 100, 1);//  sprintf("%.1f", ($goods / $total )* 100) ;
        return $course->where([['id', '=', $data['goods_id']]])->update(['course_score' => $course_score]);
    }

    /***
     * @param $data
     * @return mixed
     * 医师评分
     */
    public function updateDoctorScore($data)
    {
        $course = new Doctor();
        $total = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 3]])->count();
        $goods = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 3]])->where("score", '>', 2)->count();
        $course_score = number_format(($goods / $total) * 100, 1);//  sprintf("%.1f", ($goods / $total )* 100) ;
        return $course->where([['id', '=', $data['goods_id']]])->update(['good_evaluat' => $course_score]);
    }

    /****
     * @param $data
     * 计算商品评分
     */
    public function updateGoodsScore($data)
    {
        $course = new ProductGoods();
        $total = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 2]])->count();
        $goods = $this->where("goods_id", '=', $data['goods_id'])->where([['types', '=', 2]])->where("score", '>', 2)->count();
        $course_score = number_format(($goods / $total) * 100, 1);//  sprintf("%.1f", ($goods / $total )* 100) ;
        return $course->where([['id', '=', $data['goods_id']]])->update(['product_score' => $course_score]);
    }

    /***
     * @param $order_id
     * @return mixed
     * 修改评价状态
     */
    public function updateOrderEvaluate($order_id)
    {
        $orders = (new Order())::getOrderDetail($order_id);
        if ($orders->pay_status == 1 && $orders->delivery_status == 1 && $orders->receive_status == 1) {
            $orders->evaluate_status = 1;
            $orders->evaluate_time = date("Y-m-d H:i:s", time());
            $orders->order_status = 1;
            return $orders->save();
        }
    }

    /**
     * @param $param
     * @return mixed
     * 获取评价列表
     */
    public function getEvaluateListData($param)
    {
        $field = "id";
        $asc = "desc";
        $with = [];
        $where[] = ['types', '=', $param['types']];
        $where[] = ['goods_id', '=', $param['goods_id']];
        $page = isset($param['page']) && !empty($param['page']) ? $param['page'] : 1;
        if (isset($param['score']) && !empty($param['score'])) {  //评价
            if ($param['score'] == 1) {//倒序
                $field = "score";
                $asc = "desc";
            } else {
                $field = "score";
                $asc = "asc";
            }
        }
        if (isset($param['times']) && !empty($param['times'])) {  //时间
            if ($param['times'] == 1) {//倒序
                $field = "id";
                $asc = "asc";
            } else {
                $field = "id";
                $asc = "desc";
            }
        }
        if (isset($param['eval_type']) && !empty($param['eval_type'])) {  //评价
            if ($param['eval_type'] == 1) {  //好评
                $where[] = ['score', '>', 2];
            } elseif ($param['eval_type'] == 2) {
                $where[] = ['score', '<', 3];  //差评
            } elseif ($param['eval_type'] == 3) {
                $where[] = ['score', '<=', 3];  //中差评
            }
        }
        if ($param['types'] == 1) { //课程
            $with = ['user', 'course','reply'];
        } elseif ($param['types'] == 2) { //商品
            $with = ['user', 'goods','reply'];
        } elseif ($param['types'] == 3) { //医师医师医师
            $with = ['user', 'doctor','reply'];
        }
        $number = $this->setGoodsNumber($param);
        $result = $this->where($where)->with($with)->orderBy($field, $asc)->paginate(15, ['*'], 'page', $page);
        if (!$result) {
            $result = [];
        } else {
            $res = $result->toArray();
            $host = new Url();
            $tool = new Tool();
            foreach ($res['data'] as $k => &$v) {
                $v['images'] = $tool->addHostToImage($v['images']);
                $v['videos'] = $host::getHttpHost() . 'upload/' . $v['videos'];
                if($v['user']){
                    if(!empty($v['user']['image'])){
                        $v['user']['image'] = $host::getHttpHost() . 'upload/' . $v['user']['image'];
                    }else{
                        $v['user']['image'] = $host::getHttpHost() .'/image/default.png';
                    }
                    if($v['anonymity_state'] ==1){
                        $v['user']['name'] = "匿名买家";
                        $v['user']['image'] = $host::getHttpHost() .'/image/default.png';
                    }
                }
                $v['ins_time'] = $tool::time2Units(time() - strtotime($v['created_at']));
                if(empty($v['reply'])){
                    $v['is_reply']  =0;
                }else{
                    $v['is_reply']  =1;
                }
            }
            $result = $res;
        }
        $result['statistics'] = $number;
        return $result;
    }

    /**
     * @param $param
     * @return mixed
     * 获取评价列表
     */
    public function getAllEvaluateListData($param)
    {
        $field = "id";
        $asc = "desc";
        $where[] = ['work_id', '=', $param['work_id']];
        if (isset($param['types']) && !empty($param['types'])) {
            $where[] = ['types', '=', $param['types']];
        }
        $page = isset($param['page']) && !empty($param['page']) ? $param['page'] : 1;
        if (isset($param['is_image']) && !empty($param['is_image'])) {  //是否有图
            if ($param['is_image'] == 1) {//倒序
                $field = "is_image";
                $asc = "desc";
            } else {
                $field = "is_image";
                $asc = "asc";
            }
        }
        if (isset($param['times']) && !empty($param['times'])) {  //最新
            if ($param['times'] == 1) {//倒序
                $field = "id";
                $asc = "desc";
            } else {
                $field = "id";
                $asc = "asc";
            }
        }
        if (isset($param['eval_type']) && !empty($param['eval_type'])) {  //评价
            if ($param['eval_type'] == 1) { //好评
                $where[] = ['score', '>', 3];
            } elseif ($param['eval_type'] == 2) { //中评
                $where[] = ['score', '=', 3];
            } elseif ($param['eval_type'] == 3) { //差评
                $where[] = ['score', '<', 3];
            } elseif ($param['eval_type'] == 4) { //中差评
                $where[] = ['score', '<=', 3];
            }
        }
        $number = $this->setNumber($param); //统计数据
        $number['real_evaluate'] = $this->getStatistics($param, $number);//综合好评率和真实评价
        $result = $this->where($where)->with(['user'])->orderBy($field, $asc)->paginate(15, ['*'], 'page', $page);
        if (!$result) {
            $result = null;
        } else {
            $res = $result->toArray();
            $host = new Url();
            $tool = new Tool();
            $reply_content = new ReplyContent();
            foreach ($res['data'] as $k => &$v) {
                $v['images'] = $tool->addHostToImage($v['images']);
                $v['videos'] = $host::getHttpHost() . 'upload/' . $v['videos'];
                if(!empty($v['user'])){
                    if(!empty($v['user']['image'])){
                        $v['user']['image'] = $host::getHttpHost() . 'upload/' . $v['user']['image'];
                    }else{
                        $v['user']['image'] = $host::getHttpHost() .'/image/default.png';
                    }
                    if($v['anonymity_state'] ==1){
                        $v['user']['name'] = "匿名买家";
                        $v['user']['image'] = $host::getHttpHost() .'/image/default.png';
                    }
                }
                $v['ins_time'] = $tool::time2Units(time() - strtotime($v['created_at']));
                //获取回复内容
                $con = $reply_content->where([['evaluates_id','=',$v['id']]])->first();
                if(empty($con)){
                    $v['reply_content']  = null;
                    $v['is_reply']  =0;
                }else{
                    $v['reply_content']  = $con->toArray();
                    $v['is_reply']  =1;
                }
            }
            $result = $res;
        }
        $result['statistics'] = $number;
        return $result;
    }

    /**
     * @param $param
     * //综合好评率和真实评价
     */
    public function getStatistics($param, $number)
    {
        if (isset($param['types']) && !empty($param['types'])) { //商品类型(1:课程,2:商品,3:医师)
            $where = [];
            if ($param['types'] == 1) {   //商品类型(1:课程,2:商品,3:图文质询,4:电话预约,5:打赏)
                $where[] = ['order_type', '=', 1];
            } elseif ($param['types'] == 2) {
                $where[] = ['order_type', '=', 2];
            } elseif ($param['types'] == 3) {
                $where[] = [function ($query) {
                    $query->whereIn('order_type', ['3,4']);
                }];
            }
            $statis_num = (new Order())->where($where)->where([['work_id', '=', $param['work_id']]])->count('id');
        } else {
            $statis_num = (new Order())->where([['work_id', '=', $param['work_id']]])->count('id');
        }
        if ($statis_num > 0) {
            return (number_format(($number['all'] / $statis_num) * 100, 2));
        } else {
            return 100;
        }
    }

    /***
     * @return array
     * 统计个数
     */
    public function setNumber($param)
    {
        $data = [];
        if(isset($param['types']) && !empty($param['types'])){
            $data['goods_num'] = $this->where([['types','=',$param['types']]])->where([['score', '>', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['mid_num'] = $this->where([['types','=',$param['types']]])->where([['score', '=', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['bad_num'] = $this->where([['types','=',$param['types']]])->where([['score', '<', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['all'] = $this->where([['types','=',$param['types']]])->where([['work_id', '=', $param['work_id']]])->count("id");
        }else{
            $data['goods_num'] = $this->where([['score', '>', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['mid_num'] = $this->where([['score', '=', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['bad_num'] = $this->where([['score', '<', 3], ['work_id', '=', $param['work_id']]])->count("id");
            $data['all'] = $this->where([['work_id', '=', $param['work_id']]])->count("id");
        }
        $data['badormid_num'] = $data['mid_num'] + $data['bad_num'];
        //综合好评率=总评价条数÷好评条数
        if ($data['all'] > 0 && $data['goods_num'] >0) {
            $gre = number_format(($data['goods_num'] / $data['all']) * 100  , 2);
            if ($gre < 50) {
                $data['goods_rate'] = 50;
            } else {
                $data['goods_rate'] = $gre;
            }
        } else {
            $data['goods_rate'] = 100;
        }
        return $data;
    }

    /***
     * @return array
     * 统计个数
     */
    public function setGoodsNumber($param)
    {
        $data = [];
        $data['goods_num'] = $this->where([['score', '>', 3], ['goods_id', '=', $param['goods_id']]])->count("id");
        $data['mid_num'] = $this->where([['score', '=', 3], ['goods_id', '=', $param['goods_id']]])->count("id");
        $data['bad_num'] = $this->where([['score', '<', 3], ['goods_id', '=', $param['goods_id']]])->count("id");
        $data['all_num'] = $this->where([['goods_id', '=', $param['goods_id']]])->count("id");
        //综合好评率=总评价条数÷好评条数
        if ($data['all_num'] > 0 && $data['goods_num'] > 0) {
            $gre = number_format(($data['goods_num'] / $data['all_num']) * 100, 2);
            if ($gre < 50) {
                $data['goods_rate'] = 50;
            } else {
                $data['goods_rate'] = $gre;
            }
//           $order_num  = (new Order())
//                ->join("c_order_goods as og","c_orders.id",'=','c_order_goods.order_id')
//                ->where([["c_order_goods.goods_id","=",$param['goods_id']]])->count("c_orders.id");
//            if($order_num > 0){
//                $data['real_rate'] = number_format(( $data['all_num'] / $order_num) * 100, 2);
//            }else{
//                $data['real_rate'] = 100;
//            }
        } else {
            $data['goods_rate'] = 100;
//            $data['real_rate'] = 100;
        }
        return $data;
    }

    /**
     * @param $data
     * @return mixed
     * 评论信息
     */
    public function getInfos($data)
    {
        return $this->where("order_id", '=', $data['order_id'])
            ->where("user_id", '=', $data['user_id'])
//            ->where("relate_id", '=', $data['relate_id'])
            ->first();
    }
}
